import type { CacheKey } from './types'

const cacheFetchMap = new Map<string, Promise<any>>()

export const setCacheFetch = (cacheKey: CacheKey, fetch: Promise<any>) => {
  cacheFetchMap.set(cacheKey, fetch)

  fetch
    .then(res => {
      cacheFetchMap.delete(cacheKey)
      return res
    })
    .catch(() => {
      cacheFetchMap.delete(cacheKey)
    })
}

export const getCacheFetch = (cacheKey: CacheKey) => {
  return cacheFetchMap.get(cacheKey)
}

export const clearCacheFetch = (cacheKey?: CacheKey) => {
  if (cacheKey) {
    cacheFetchMap.delete(cacheKey)
  } else {
    cacheFetchMap.clear()
  }
}
